package com.ericsson.springintegrationtest.service;

import com.ericsson.springintegrationtest.model.User;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by IntelliJ IDEA.
 * User: lbonacina
 * Date: 25/07/11
 * Time: 15.59
 */
@Service("userService")
public class UserServiceImpl extends ServiceDefaultImpl implements UserService {

// ------------------------ INTERFACE METHODS ------------------------
// --------------------- Interface UserService ---------------------
    @Override
    @Transactional(readOnly = true)
    @SuppressWarnings(value = "unchecked")
    public List<User> findAll() {
        return (List<User>) getEntityManager().createQuery("select u from User u").getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public User findByName(String firstName, String lastName) {

        try {
            return (User) getEntityManager().createQuery("select u from User u where u.firstName = :firstName and u.lastName = :lastName").setParameter("firstName", firstName).setParameter("lastName", lastName).getSingleResult();
        }
        catch (NoResultException noResultException) {
            return null ;
        }
        catch (NonUniqueResultException nonUniqueResultException) {
            // shoud not happen
            throw new RuntimeException("SOMETHINH IS WRONG HERE !") ;
        }
    }
}
